# 程序版
from  selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from urllib import parse, request
import urllib.request
import time
import re
import json

def login(username,password,name):
    # 登陆并获取cookies,tbs
    login_url = 'https://passport.baidu.com/v2/?login&fr=old&login'
    driver = webdriver.PhantomJS()
    try:
        driver.get(login_url)
        driver.find_element_by_id('TANGRAM__PSP_3__footerULoginBtn').click()
        driver.find_element_by_name('userName').send_keys(username)
        driver.find_element_by_name('password').send_keys(password)
        driver.find_element_by_name('password').send_keys(Keys.ENTER)
    except Exception as e:
        print(e)
    sleep(2)
    curpage_url = driver.current_url
    if curpage_url == login_url:
        pass
    print('登录成功，当前账号为：{}'.format(username))
    cookie = [item["name"] + "=" + item["value"] for item in driver.get_cookies()]
    cookiestr = ';'.join(item for item in cookie)
    driver.get('https://tieba.baidu.com/f?ie=utf-8&kw=' + parse.quote(name))
    pat = r': "([0-9a-z]+)"'
    pat_res = re.findall(pat, driver.page_source)[0]
    return cookiestr, pat_res
def post_form(title,content,pat_res,cookiestr):
    data= '''ie:utf-8
    kw:光有米
    fid:25530455
    tid:0
    vcode_md5:
    floor_num:0
    rich_text:1
    tbs:9219732bb6907e641517803394
    content:qiuqiq
    basilisk:1
    title:qiuqiu
    prefix:
    mouse_pwd:97,96,104,124,102,96,99,101,89,97,124,96,124,97,124,96,124,97,124,96,124,97,124,96,124,97,124,96,89,97,97,96,99,102,89,97,105,98,96,124,97,96,104,96,15178029837800
    mouse_pwd_t:1517799298483
    mouse_pwd_isclick:1
    __type__:thread
    _BSK:JVwAV2cLBE0kGUA6TW4XAUhdZWZjF0UbHD5VBH8Vd2ljAHxNQXhmR1dVKDkHWUMGJwgtVRA0Vyp2V0EYZWpKSjEcRTpBLxlUDzplKngJV1kNb10GdwV3Z2EFYV4fazROVwl9MQVBWQxlCjoFXGoYdW5PVlNwABUHZwYCfVtsRwBSV2l1ORRXDR45FVMgGWQ+YxJqTwF5dUpFBmxmSA9LWmsSf1IfPEsiclwUUmcLBmYqD1ozDS1ZBURXZX8NTBtTUToUBgthZmFhHmBUEx4LKkMHdHclXVoFLH86VjU5TGhrTVZNdgcEAw49ZxItYFZcAwwgdx1AFlxRZEdlLUcpPTQfZVodeWpPTQtueVwaCjwLWjBDDTVKaGhQU012CBIfa0cTDAAqF0IDSHBkbQtGARxhRUp3F3xwJUIlCh9rIExXCX8ZMWFmS2UKKAdcahghPxISBmkTUBpnTxE5FCIVRAMIK3cuSiZDTCQJQW0cZitxaz4ORyAyGFVQMjMBcAoUawR9XU9yAmcqDBQGaRNXGGdPEysTORMcSAZ3dWAFRAcNfUsENQRkanMVZy0We3YJF0B4ZVYIGShsGm0BH2YKdj1JVlNyCBdKc0VVblR9QQdTXndubQBHBRt6IwRpFzFkcwpyHEMsIR4dYCQ5EEVPGiBbc1cfM1AiLVINDCZQSHgxGkE+BilaQw8UNj41SyZDUT8GQSAZMTUzWzkbYD0rDxRUOB4KS0VFIEY7UQY1XAMcUhYGJ1pNXwwbVzoZKRJ0KEsqOT5AA15dKAhULFAoJDBEOQBdKCYOGl8oIwEBRQctTSldHTVXNTcbDxckRU1EK1lcMQUpAFkJAig4LkwaWRIuFV81QSl8IkQ/Hx8mNBgbHzw7AV9eRSpHMVIXIlVrLgwODjVFCFs3HF0rTT4TQR8CNiMbSxxaXzkOSStzNDE8VXwMUicnGBlyMz4JTF4AJkYZRh89XWssGxAWIEJQYiEZVhwAIBpSCwQuezlEG1RbIS5CKVAFMT1cMg5QImZRV15sdV4PSAg6QTNdDTtnJhIIUQkiEwgJMkQRZUMCI3wmRWl1LhdXDR58UhdyAn9pZwlpQxE5dl9PEQo+Ch4YS2UKMQVcahh1bk9WU3AAFQdnAgF9W244ZSYrZ3t4SUQVBG8dTmh2CHIs'''
    form_data = {}
    a = data.replace('\n',':').split(':')
    for i in range(34):
        if i%2 ==0:
            form_data[a[i]] = a[i+1]
    # 修改postdata数据
    form_data['mouse_pwd_t'] = time.time()
    form_data['tbs'] = pat_res
    form_data['title'] =title
    form_data['content'] = content
    data = urllib.parse.urlencode(form_data).encode('utf-8')
    post_url = 'https://tieba.baidu.com/f/commit/thread/add'
    headers = {
        'cookie': cookiestr,
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.3964.2 Safari/537.36'
    }
    req = request.Request(post_url, data=data,  headers=headers)
    data = request.urlopen(req)
    msg = json.loads(data.read().decode('utf-8'))['err_code']
    if msg  == 0:
        print('发布成功')

if __name__ == '__main__':
    username = '18500284177 '
    password = 'aq918927'
    name = '光有米'
    cookiestr, pat_res = login(username, password,name)
    title = '无法说明我爱你'
    content = '无法说明我爱你'
    post_form(title, content, pat_res, cookiestr)